import { Injectable } from '@nestjs/common';
import { CreateScriptDto } from './dto/create-script.dto';
import { UpdateScriptDto } from './dto/update-script.dto';
import { Core } from "src/core";
import { ObjectId } from "mongodb";

@Injectable()
export class ScriptService {
  create(createScriptDto: CreateScriptDto) {
    return this.getCollection().insertOne({
      ...createScriptDto,
      createdAt: new Date(),
      updatedAt: new Date()
    });
  }

  async findAll() {
    const ary = await this.getCollection().find({}).toArray();
    return ary;
  }

  async findOne(id: string) {
    const ary = await this.getCollection().findOne({ _id: new ObjectId(id) });
    return ary;
  }

  async update(id: string, updateScriptDto: UpdateScriptDto) {
    const filter = { _id: new ObjectId(id) };
    const update = { $set: { ...updateScriptDto, updatedAt: new Date() } };
    const result = await this.getCollection().updateOne(filter, update);
    return `Updated ${result.modifiedCount} document(s)`;
  }

  async remove(id: string) {
    const insertResult = await this.getCollection().deleteOne({ _id: new ObjectId(id) });
    return insertResult.deletedCount.toString();
  }

  getCollection() {
    return Core.ins.db.collection("script");
  }

}
